package cn.tedu.charging.utils;

import cn.tedu.charging.account.pojo.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class JwtUtil {

    private static String secretKey;

    @Value("${charging.jwt.secret-key}")
    public void setSecretKey(String secretKey) {
        JwtUtil.secretKey = secretKey;
    }

    // 生成Token的方法
    public static String generate(String id) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("user_id", id);

        String jwt = Jwts.builder()
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
        log.debug(jwt);
        return jwt;
    }

    //解析token
    public static String parse(String jwt) {
        Claims claims = Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
        String id = claims.get("user_id", String.class);
        log.debug("user_id={}", id);
        return id;
    }
}
